package ua.amsoft.brelok.widget;

import ua.amsoft.brelok.constant.Constants;
import ua.amsoft.brelok.manager.PreferencesManager;
import ua.amsoft.brelok.service.UpdateService;
import ua.amsoft.brelok.util.DateTimeUtils;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;

/**
 * @author Tair Mustafaiev
 */
public class NetworkConnectivityListener extends BroadcastReceiver {
    
    private static final String TAG = NetworkConnectivityListener.class.getName();
    
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.i(NetworkConnectivityListener.TAG, "Listener started invocation");
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            final boolean noConnectivity = intent.getBooleanExtra(
                    ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            if (!noConnectivity) {
                callUpdateService(context);
            }
            Log.i(NetworkConnectivityListener.TAG, "Listener finished invocation");
        }
    }
    
    /**
     * Calls an {@link UpdateService} for start updating after Network
     * connection was resumed
     * 
     * @param context - {@link Context}
     */
    private void callUpdateService(final Context context) {
        final PreferencesManager preferencesManager = new PreferencesManager();
        final String timeFrom = preferencesManager.getPrefByName(context,
                Constants.PREF_UPDATING_TIME_FROM, "09:00");
        final String timeTill = preferencesManager.getPrefByName(context,
                Constants.PREF_UPDATING_TIME_TILL, "19:00");
        if (DateTimeUtils.isNowUpdatablePeriod(timeFrom, timeTill)) {
            final Intent updateIntent = new Intent(context, UpdateService.class);
            final PendingIntent pendingIntent = PendingIntent.getService(context,
                    (int) (Math.random() * 10000), updateIntent, 0);
            try {
                pendingIntent.send();
                Log.i(NetworkConnectivityListener.TAG,
                        "Listener sent pending intent to UpdateService");
            } catch (final CanceledException e) {
                Log.e(NetworkConnectivityListener.TAG, e.getLocalizedMessage());
            }
        }
    }
}
